<template>
  <div class="main">
    标题：<el-input v-model="article.title" placeholder="请输入标题" style="width:25%" :disabled="this.readOnly" class="edit-item"></el-input>
    简介：<el-input v-model="article.intro" placeholder="请输入简介" style="width:25%" :disabled="this.readOnly" class="edit-item"></el-input>
    <el-button v-if="article.id" type="danger" icon="el-icon-delete" @click="deleteArticle(article)" circle class="edit-item"></el-button>
    <el-button :disabled="!readOnly" type="primary" icon="el-icon-edit" @click="editorArticle" circle class="edit-item"></el-button>
    <el-button :disabled=" readOnly" type="primary" icon="el-icon-tickets" @click="save" circle class="edit-item"></el-button>
    <el-button type="primary" icon="el-icon-back" @click="back" circle class="edit-item"></el-button>
    <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editor"
        :defaultConfig="toolbarConfig"
        :mode="mode"
    >
      <button>save</button>
    </Toolbar>
    <Editor
        style="height: 500px; overflow-y: hidden;"
        v-model="article.article"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="onCreated"
        @onDestroyed="onDestroy"
    >
    </Editor>
  </div>
</template><script>
import Vue from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {reqGetArticleText, reqUploadFile2ArticleUrl} from "@/api/article";
import { Boot } from '@wangeditor/editor'
import markdownModule from '@wangeditor/plugin-md'
import ArticleList from "@/views/article/ArticleList";
import {Article} from "@/class/Article";
let saveArticleMethod,editArticleMethod
export default Vue.extend({
  components: { Editor, Toolbar },
  data() {
    return {
      editor: null,
      html: '<p>hello</p>',
      toolbarConfig: {
        excludeKeys:["underline"]
      },
      editorConfig: {
        placeholder: `请输入内容...<br>
&nbsp; 支持MarkDown<br>
&nbsp; &nbsp; 标题&nbsp;&nbsp;&nbsp;#<br>
&nbsp; &nbsp; 列表&nbsp;&nbsp;&nbsp;- + *<br>
&nbsp; &nbsp; 引用&nbsp;&nbsp;&nbsp;><br>
&nbsp; &nbsp; 分割线&nbsp;&nbsp;&nbsp;---<br>
&nbsp; &nbsp; 代码块&nbsp;&nbsp;&nbsp;\`\`\`js<br>
`,
        readOnly:true,
        MENU_CONF: {
          uploadImage:{
            server: reqUploadFile2ArticleUrl,
            fieldName: 'file',
            customInsert(res, insertFn) {
              insertFn(res.data, "", "").then(result1=>{
                saveArticleMethod().then(result2=>{
                  editArticleMethod()
                })
              })
            },
            headers: {
            },
            maxFileSize: 100 * 1024 * 1024, // 1M
          },
          insertImage:{
            onInsertedImage:this.onInsertedImage
          },
          editImage:{
            onUpdatedImage:this.onEditImage
          }
        },
      },
      readOnly:true,
      mode: 'default', // or 'simple'
      article:void 0,
      uploadImageList:[]
    }
  },
  methods: {
    onInsertedImage(image){
      this.uploadImageList.push(image)
    },
    onEditImage({src}){
      console.log("edit"+src)
    },
    async get_article_data() {
      let result;
      if(this.$route.query.id) {
        result = await Article.getArticleById(this.$route.query.id)
        if(result) {
          this.article = result
        }else {
          this.warningMessage("not found")
          this.$router.push(ArticleList)
        }
      }else{
        result = await Article.createArticle()
        if(result){
          this.article=result
        }else{
          this.warningMessage("添加文章ID时失败")
          this.$router.push(ArticleList)
        }
      }
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      this.editorArticle()
    },
    onDestroy(){
      let imageNow = this.editor.getElemsByType("image");
      console.log("nowImage",imageNow)
      console.log("uploadImage",this.uploadImageList)

    },
    async save() {
      if(this.article.title===''){
        this.warningMessage("题目不能为空");
        return
      }

      if(this.article.intro===''){
        const reg = /[\'\"\\\/\b\f\n\r\t]/g
        let result = this.editor.getText().replaceAll(reg,'')
        this.article.intro=result.slice(0,10)
        console.log(this.article)
      }
      const result = await this.article.updateArticle()
      if (result) {
        this.successMessage( "更新成功1");
      }
      this.editor.disable()
      this.readOnly=true;
    },
    async deleteArticle(article) {
      article.deleteArticle().then(result=>{
        if(result){
          this.successMessage("删除成功");
          this.$router.push(ArticleList)
        }
      });
    },
    editorArticle(){
      this.editor.enable();
      this.readOnly=false;
    },
    back(){
      this.$router.push(ArticleList)
    }
  },
  async created() {
    this.get_article_data().then(result=>{
      Boot.registerModule(markdownModule)
      this.editorConfig.MENU_CONF.uploadImage.headers.articleId = this.article.id;
      saveArticleMethod=this.save
      editArticleMethod=this.editorArticle
    });
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
    reqGetArticleText("article edit end")
  }
})
</script>
<style scoped>
@import "@wangeditor/editor/dist/css/style.css";
.main{
  border: 2px solid #ccc;
  border-radius: 5px;
  padding: 5px;
}
.edit-item{
 padding: 5px;
}
</style>